package com.ruoyi.web.controller.comment;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.client.domain.SysSell;
import com.ruoyi.client.service.ISysSellService;
import com.ruoyi.common.annotation.Anonymous;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Component
@Anonymous
@ServerEndpoint(value = "/test/oneToMany")
public class OneToManyWebSocket {
    /*记录当前在线连接数*/
    private static AtomicInteger onlineCount = new AtomicInteger(0);
    /*记录当前在线客户端*/
    public static Map<String, Session> clients=new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) throws InterruptedException, JsonProcessingException {
        onlineCount.incrementAndGet(); // 在线数加1
        clients.put(session.getId(), session);
        log.info("有新连接加入：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
        //开始模拟数据
        for (int i = 0; i < 1000; i++) {
            Thread.sleep(1000);//没s发一次
            if(i%10==0){
                //发送报警数据
                this.sendMessage(1369+"", session);
            }else {
                //final List<SysSell> sellList = iSysSellService.sysSellList("sz000001");

//                否则就发送正常数据
                this.sendMessage(600+"", session);
            }
        }


    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        onlineCount.decrementAndGet(); // 在线数减1
        clients.remove(session.getId());
        log.info("有一连接关闭：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     *            客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("服务端收到客户端[{}]的消息:{}", session.getId(), message);
        this.sendMessage(message, session);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 群发消息
     *
     * @param message
     *            消息内容
     */
    private void sendMessage(String message, Session fromSession) {
        //遍历所有在线客户端
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            //取得每一个客户端
            Session toSession = sessionEntry.getValue();
            // 排除掉自己
            if (!fromSession.getId().equals(toSession.getId())) {
                log.info("服务端给客户端[{}]发送消息{}", toSession.getId(), message);
                //给每个客户端发送信息
                toSession.getAsyncRemote().sendText(message);
            }
        }
    }
}
